//
//  File.swift
//  casdon_swiftUI
//
//  Created by casdon on 2025/4/24.
//

import Combine
import AuthenticationServices

struct WechatAuthResult {
    let socialCode: String
    let socialState: String
}
enum WeChatAuthorizeError: Error {
    case timeout
    case invalidResponse
}

struct WechatAuthStep: LoginStep {
    struct InputData {} // 无需输入参数

    private let subject = PassthroughSubject<WechatAuthResult, Error>()

        func execute(_ input: InputData) -> AnyPublisher<WechatAuthResult, Error> {
            launchWeChatForAuth()
            // 等待 View 层注入结果
            return subject
                .timeout(.seconds(60), scheduler: RunLoop.main, customError: { WeChatAuthorizeError.timeout })
                .eraseToAnyPublisher()
        }

        // 外部注入，获取微信授权结果
        func handleOpenURL(_ url: URL) {
            // 微信授权跳转回来
            if !url.absoluteURL.absoluteString.contains(WECHAT_UNISAL_LINK)
            {
                return
            }
            let code = url.absoluteString.parsedURL?.queryItems["code"]
            let state = url.absoluteString.parsedURL?.queryItems["state"]
            guard let code = code , let state = state else {
                
                subject.send(completion: .failure(WeChatAuthorizeError.invalidResponse))
                Logger.log(.error, message: "微信授权失败", tag: .login)
                return
            }
            AuthManager.shared.saveWeChatAuthInfo(code: code , state: state)
            let result = WechatAuthResult(socialCode: code, socialState: state)
            subject.send(result)
        }
    
    // 拉起微信app，发起授权请求
   private func launchWeChatForAuth() {
        guard let topVC = UIApplication.topViewController() else {
            print("无法获取顶层视图控制器")
            return
        }

        let req = SendAuthReq()
        req.scope = ThirdParty.WX_authScope
        req.state = UUID.init().uuidString
        req.openID = ThirdParty.WX_OpenID

       WXApi.sendAuthReq(req, viewController: topVC, delegate: nil)
    }
}

